package com.ericzong.util.file;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class ImageUtils
{
	/**
	 * 水平合并图片
	 * 
	 * @param images 一组图片文件，期望高度一致
	 * @param path 输出合并图片的路径
	 * 
	 * @throwsIOException
	 */
	public static void mergeImage(File[] images, String path) throws IOException
	{
		BufferedImage[] buffImages = new BufferedImage[images.length];
		int width = 0;

		for (int i = 0; i < buffImages.length; i++)
		{
			buffImages[i] = ImageIO.read(images[i]);
			width += buffImages[i].getWidth();
		}

		int height = buffImages[0].getHeight();
		int type = 5; // buffImages[0].getType();
		int x = 0;
		BufferedImage img = new BufferedImage(width, height, type);

		for (int i = 0; i < buffImages.length; i++)
		{
			img.createGraphics().drawImage(buffImages[i], x, 0, null);
			x += buffImages[i].getWidth();
		}

		ImageIO.write(img, "png", new File(path));
	}

	/**
	 * @param src 原图片路径
	 * @param dest 裁剪后图片路径
	 * @param rect 裁剪范围
	 * @return
	 * @throws IOException
	 */
	public static File cutImage(String src, String dest, Rectangle rect) throws IOException
	{
		String extName = src.substring(src.lastIndexOf("."));
		
		Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(extName);
		ImageReader reader = iterator.next();
		File destFile = null;

		try (InputStream in = new FileInputStream(src);
		        ImageInputStream iis = ImageIO.createImageInputStream(in);)
		{
			reader.setInput(iis, true);
			ImageReadParam param = reader.getDefaultReadParam();
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			destFile = new File(dest);
			ImageIO.write(bi, extName, destFile);
		}

		return destFile;
	}

}
